// IM初始化
 window.JIM = new JMessage({
         // debug : true
     });
 	$.ajax({
 	url:'http://liuqingwushui.top/api/imchat.php',
 	data:{},
 	success:function(data){
 	JIM.init({
 		"appkey" : data.appkey,
 		"random_str" : data.random_str,
 		"signature" : data.signature,
 		"timestamp" : data.timestamp,
 		"flag" : 0
 	}).onSuccess(function(data) {
 		console.log('success:' + JSON.stringify(data));
		ready();
 	}).onFail(function(data) {
 		console.log('error:' + JSON.stringify(data))
 		 });
 		},
 		error:function(data){
 			mui.alert("鉴权失败");
 		}
 			});

function ready(){
	var user= localStorage.getItem("account");
	var pass= localStorage.getItem("pass");
        JIM.login({
            'username' : user,
			'password':  pass
        }).onSuccess(function(data) {
            console.log(data);
			localStorage.setItem("account", data.username);
			
			
			//消息实时监听
		   JIM.onMsgReceive(function(data) {
                console.log(data);
            });
			//用户信息变更监听
           JIM.onUserInfUpdate(function(data) {
                console.log('onUserInfUpdate : ' + JSON.stringify(data));
            });
			//业务事件同步监听
			// JIM.onSyncEvent(function(data) {
   //              console.log('onSyncEvent : ' + JSON.stringify(data));
   //          });
			//消息已读数变更事件实时监听
			JIM.onMsgReceiptChange(function(data){
			    console.log('onMsgReceiptChange : ' + JSON.stringify(data));
			});
			//消息已读数变更事件同步监听
			JIM.onSyncMsgReceipt(function(data){
			    console.log('onSyncMsgReceipt : ' + JSON.stringify(data));
			});
			//会话未读数变更监听（多端在线）
			JIM.onMutiUnreadMsgUpdate(function(data){
			    console.log('onConversationUpdate : ' + JSON.stringify(data));
			});
			//消息透传监听
		    JIM.onTransMsgRec(function(data){
			    console.log('onTransMsgRec : ' + JSON.stringify(data));
			});
			//获取会话列表
			 JIM.getConversation().onSuccess(function(data) {
			                  console.log(data);
							  var coum=data.conversations.length
							  var i=0;
							  run();
							  function run(){
							  	if(i!=data.conversations.length&&data.conversations[i].type==3){
									var name=data.conversations[i].nickName;
									var username=data.conversations[i].username;
									var time=data.conversations[i].mtime;
									var unread_msg_count=data.conversations[i].unread_msg_count
									var k=i;
							  	JIM.getResource({'media_id' : data.conversations[i].avatar,}).onSuccess(function(src) {
									 $('#chatlist').append("<li onclick=joinroom('"+name+"','"+username+"') class='mui-table-view-cell mui-media'><a href='javascript:;'><img class='mui-media-object mui-pull-left' src='"+src.url+"'><div class='mui-media-body'>"+name+"<span class='time'>"+getShortDate(time)+"</span><p class='mui-ellipsis'>想要这样一间小木屋，夏天挫冰吃瓜，冬天围炉取暖.</p></div><span class='mui-badge mui-badge-danger'>"+unread_msg_count+"</span></a></li>");
									
							  	 }).onFail(function(src){
										 $('#chatlist').append("<li  onclick=joinroom('"+name+"','"+username+"')  class='mui-table-view-cell mui-media'><a href='javascript:;'><img class='mui-media-object mui-pull-left' src='img/touxiang.png'><div class='mui-media-body'>"+name+"<span class='time'>"+getShortDate(time)+"</span><p class='mui-ellipsis'>想要这样一间小木屋，夏天挫冰吃瓜，冬天围炉取暖.</p></div><span class='mui-badge mui-badge-danger'>"+unread_msg_count+"</span></a></li>");
								 })
							  	if(i<data.conversations.length){i++;run();}
							  	else{console.log("会话列表渲染完成!");}
							  	}else{console.log("会话列表渲染完成!");}
							  }
							  //异步数据同步
							  // for(var i=0;i<data.conversations.length;i++){
								 //   if(data.conversations[i].type==3){
									//     JIM.getResource({
									//                     'media_id' : data.conversations[i].avatar,
									//                   }).onSuccess(function(src) {
									// 					  console.log(i);
									//                       $('#chatlist').append("<li class='mui-table-view-cell mui-media'><a href='javascript:;'><img class='mui-media-object mui-pull-left' src='"+src.url+"'><div class='mui-media-body'>"+data.conversations[i].nickname+"<span class='time'>"+getShortDate(data.conversations[i].mtime)+"</span><p class='mui-ellipsis'>想要这样一间小木屋，夏天挫冰吃瓜，冬天围炉取暖.</p></div><span class='mui-badge mui-badge-danger'>"+data.conversations[i].unread_msg_count+"</span></a></li>");
									//                   }).onFail(function(data) {
									//                      
									//                   });
								 //   }
							  // }
			               })
        }).onFail(function(data) {
             mui.openWindow({url:'login.html'})
        }).onTimeout(function(data) {
            mui.openWindow({url:'login.html'})
        });
		}
		function getShortDate(time) {
			var date = new Date(time*1000);
			var hour = date.getHours().toString();
			var minutes = date.getMinutes().toString();
			var seconds = date.getSeconds().toString();
			if (hour < 10) {
				hour = "0" + hour;
			}
			if (minutes < 10) {
				minutes = "0" + minutes;
			}
			if (seconds < 10) {
				seconds = "0" + seconds;
			}
			return hour + ":" + minutes;
		}
		function joinroom(nickname,username){
			console.log("加入聊天室:"+username);
			 JIM.resetUnreadCount({
			                            'username' : username
			                           });
			window.location.href="friendroom.html?nickname="+encodeURI(nickname)+"&username="+encodeURI(username)+"";
		}